#include "libgenbank.h"
#include "libfasta.h"

char reverse_bp(char c)
{
    if (c == 'a')
        return 't';
    if (c == 't')
        return 'a';
    if (c == 'g')
        return 'c';
    return 'g';
}

void print_sequence(struct sequence tmp, FILE *fp)
{
    int i = 0, count = 0;
    char c;
    if (tmp.compl == 1)
        i = strlen(tmp.seq) - 1;
    while (i >= 0 && ((c = tmp.seq[i]) != '\0'))
        {
            if (c == 'a' || c == 'c' || c == 'g' || c == 't')
            {
                if (tmp.compl == 1)
                    c = reverse_bp(c);
                c -= 32;
                if (count != 0 && count % 60 == 0)
                    fputc('\n', fp);
                fputc(c, fp);
                count++;
            }
            if (tmp.compl == 1)
                i--;
            else
                i++;
        }
    fputc('\n', fp);
}

void output_CDS(struct sequence *sequences, char *file_name, int length)
{
    strcat(file_name, ".fasta");
    FILE *foutput;
    foutput = fopen(file_name, "w");
    int flag = 0;
    for (int i = 0; i < length; i++)
    {
        if (sequences[i].seq[0])
        {
            int j = i;
            if (j == 0 || sequences[j - 1].name)
                flag = 0;
            while (!sequences[j].name)
                j++;
            if (flag == 0)
            {
                fputc('>', foutput);
                fputs(sequences[j].name, foutput);
                fputc('\n', foutput);
                flag = 1;
            }
            print_sequence(sequences[i], foutput);
        }
    }
    fclose(foutput);
}

void gb_to_fasta(char *file_name)
{
    struct sequence *sequences = read_seq(file_name);
    int n = interval_number(file_name);
    output_CDS(sequences, file_name, n);
    printf("123\n");
    for (int i = 0; i < n; ++i) {
      if (strlen(sequences[i].seq) != 0)
        free(sequences[i].seq);
      if (sequences[i].name)
	free(sequences[i].name);
    }
    printf("123\n");
      free(sequences);
}
